//////////////////////////////////////////////////////////////////////////
// Copyright 2019 The Aerospace Corporation
//
// This file is part of SatCat5.
//
// SatCat5 is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// SatCat5 is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with SatCat5.  If not, see <https://www.gnu.org/licenses/>.
//////////////////////////////////////////////////////////////////////////

#include "ethernet.h"

// STD includes
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

// System includes
#include <sys/ioctl.h>
#include <sys/socket.h>

// Network includes
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <net/if.h>

// Enable CRC diagnostics?
#define DEBUG_CRC_VERBOSE   0

// Table to calculate CRC values
static const uint32_t CRC_TABLE[256] = {
    0x00000000u, 0x77073096u, 0xEE0E612Cu, 0x990951BAu,
    0x076DC419u, 0x706AF48Fu, 0xE963A535u, 0x9E6495A3u,
    0x0EDB8832u, 0x79DCB8A4u, 0xE0D5E91Eu, 0x97D2D988u,
    0x09B64C2Bu, 0x7EB17CBDu, 0xE7B82D07u, 0x90BF1D91u,
    0x1DB71064u, 0x6AB020F2u, 0xF3B97148u, 0x84BE41DEu,
    0x1ADAD47Du, 0x6DDDE4EBu, 0xF4D4B551u, 0x83D385C7u,
    0x136C9856u, 0x646BA8C0u, 0xFD62F97Au, 0x8A65C9ECu,
    0x14015C4Fu, 0x63066CD9u, 0xFA0F3D63u, 0x8D080DF5u,
    0x3B6E20C8u, 0x4C69105Eu, 0xD56041E4u, 0xA2677172u,
    0x3C03E4D1u, 0x4B04D447u, 0xD20D85FDu, 0xA50AB56Bu,
    0x35B5A8FAu, 0x42B2986Cu, 0xDBBBC9D6u, 0xACBCF940u,
    0x32D86CE3u, 0x45DF5C75u, 0xDCD60DCFu, 0xABD13D59u,
    0x26D930ACu, 0x51DE003Au, 0xC8D75180u, 0xBFD06116u,
    0x21B4F4B5u, 0x56B3C423u, 0xCFBA9599u, 0xB8BDA50Fu,
    0x2802B89Eu, 0x5F058808u, 0xC60CD9B2u, 0xB10BE924u,
    0x2F6F7C87u, 0x58684C11u, 0xC1611DABu, 0xB6662D3Du,
    0x76DC4190u, 0x01DB7106u, 0x98D220BCu, 0xEFD5102Au,
    0x71B18589u, 0x06B6B51Fu, 0x9FBFE4A5u, 0xE8B8D433u,
    0x7807C9A2u, 0x0F00F934u, 0x9609A88Eu, 0xE10E9818u,
    0x7F6A0DBBu, 0x086D3D2Du, 0x91646C97u, 0xE6635C01u,
    0x6B6B51F4u, 0x1C6C6162u, 0x856530D8u, 0xF262004Eu,
    0x6C0695EDu, 0x1B01A57Bu, 0x8208F4C1u, 0xF50FC457u,
    0x65B0D9C6u, 0x12B7E950u, 0x8BBEB8EAu, 0xFCB9887Cu,
    0x62DD1DDFu, 0x15DA2D49u, 0x8CD37CF3u, 0xFBD44C65u,
    0x4DB26158u, 0x3AB551CEu, 0xA3BC0074u, 0xD4BB30E2u,
    0x4ADFA541u, 0x3DD895D7u, 0xA4D1C46Du, 0xD3D6F4FBu,
    0x4369E96Au, 0x346ED9FCu, 0xAD678846u, 0xDA60B8D0u,
    0x44042D73u, 0x33031DE5u, 0xAA0A4C5Fu, 0xDD0D7CC9u,
    0x5005713Cu, 0x270241AAu, 0xBE0B1010u, 0xC90C2086u,
    0x5768B525u, 0x206F85B3u, 0xB966D409u, 0xCE61E49Fu,
    0x5EDEF90Eu, 0x29D9C998u, 0xB0D09822u, 0xC7D7A8B4u,
    0x59B33D17u, 0x2EB40D81u, 0xB7BD5C3Bu, 0xC0BA6CADu,
    0xEDB88320u, 0x9ABFB3B6u, 0x03B6E20Cu, 0x74B1D29Au,
    0xEAD54739u, 0x9DD277AFu, 0x04DB2615u, 0x73DC1683u,
    0xE3630B12u, 0x94643B84u, 0x0D6D6A3Eu, 0x7A6A5AA8u,
    0xE40ECF0Bu, 0x9309FF9Du, 0x0A00AE27u, 0x7D079EB1u,
    0xF00F9344u, 0x8708A3D2u, 0x1E01F268u, 0x6906C2FEu,
    0xF762575Du, 0x806567CBu, 0x196C3671u, 0x6E6B06E7u,
    0xFED41B76u, 0x89D32BE0u, 0x10DA7A5Au, 0x67DD4ACCu,
    0xF9B9DF6Fu, 0x8EBEEFF9u, 0x17B7BE43u, 0x60B08ED5u,
    0xD6D6A3E8u, 0xA1D1937Eu, 0x38D8C2C4u, 0x4FDFF252u,
    0xD1BB67F1u, 0xA6BC5767u, 0x3FB506DDu, 0x48B2364Bu,
    0xD80D2BDAu, 0xAF0A1B4Cu, 0x36034AF6u, 0x41047A60u,
    0xDF60EFC3u, 0xA867DF55u, 0x316E8EEFu, 0x4669BE79u,
    0xCB61B38Cu, 0xBC66831Au, 0x256FD2A0u, 0x5268E236u,
    0xCC0C7795u, 0xBB0B4703u, 0x220216B9u, 0x5505262Fu,
    0xC5BA3BBEu, 0xB2BD0B28u, 0x2BB45A92u, 0x5CB36A04u,
    0xC2D7FFA7u, 0xB5D0CF31u, 0x2CD99E8Bu, 0x5BDEAE1Du,
    0x9B64C2B0u, 0xEC63F226u, 0x756AA39Cu, 0x026D930Au,
    0x9C0906A9u, 0xEB0E363Fu, 0x72076785u, 0x05005713u,
    0x95BF4A82u, 0xE2B87A14u, 0x7BB12BAEu, 0x0CB61B38u,
    0x92D28E9Bu, 0xE5D5BE0Du, 0x7CDCEFB7u, 0x0BDBDF21u,
    0x86D3D2D4u, 0xF1D4E242u, 0x68DDB3F8u, 0x1FDA836Eu,
    0x81BE16CDu, 0xF6B9265Bu, 0x6FB077E1u, 0x18B74777u,
    0x88085AE6u, 0xFF0F6A70u, 0x66063BCAu, 0x11010B5Cu,
    0x8F659EFFu, 0xF862AE69u, 0x616BFFD3u, 0x166CCF45u,
    0xA00AE278u, 0xD70DD2EEu, 0x4E048354u, 0x3903B3C2u,
    0xA7672661u, 0xD06016F7u, 0x4969474Du, 0x3E6E77DBu,
    0xAED16A4Au, 0xD9D65ADCu, 0x40DF0B66u, 0x37D83BF0u,
    0xA9BCAE53u, 0xDEBB9EC5u, 0x47B2CF7Fu, 0x30B5FFE9u,
    0xBDBDF21Cu, 0xCABAC28Au, 0x53B39330u, 0x24B4A3A6u,
    0xBAD03605u, 0xCDD70693u, 0x54DE5729u, 0x23D967BFu,
    0xB3667A2Eu, 0xC4614AB8u, 0x5D681B02u, 0x2A6F2B94u,
    0xB40BBE37u, 0xC30C8EA1u, 0x5A05DF1Bu, 0x2D02EF8Du
};

// Size of the ethernet header
#define ETHERNET_HEADER_SIZE    14
#define ETHERNET_TYPE           3
#define MAC_ADDRESS_SIZE        6

ethernet_if::ethernet_if(const char* interface)
    : m_socket_fd(-1)
    , m_interface_idx(-1)
{
    // Open a raw packet socket, and exit if failed
    m_socket_fd = socket(AF_PACKET, SOCK_RAW, htons(ETHERNET_TYPE));
    if (m_socket_fd < 0) {
        printf("%s\n", strerror(errno));
        close(); return;
    }

    // Gets the index of our interface
    struct ifreq interface_info;
    memset(&interface_info, 0, sizeof(struct ifreq));
    strncpy(interface_info.ifr_name, interface, strlen(interface));
    if (ioctl(m_socket_fd, SIOCGIFINDEX, &interface_info) < 0) {
        close(); return;
    }
    m_interface_idx = interface_info.ifr_ifindex;

    // Set the interface to be in promiscuous mode
    struct ifreq interface_opts;
    memset(&interface_opts, 0, sizeof(struct ifreq));
    strncpy(interface_opts.ifr_name, interface, strlen(interface));
    if (ioctl(m_socket_fd, SIOCGIFFLAGS, &interface_opts) < 0) {
        close(); return;
    }
    interface_opts.ifr_flags |= IFF_PROMISC;
    if (ioctl(m_socket_fd, SIOCSIFFLAGS, &interface_opts) < 0) {
        close(); return;
    }

    // Allow the socket to be reused
    int listen = 1;
    if (setsockopt(m_socket_fd, SOL_SOCKET, SO_REUSEADDR, &listen, sizeof(int)) < 0) {
        close(); return;
    }

    // Attempt to bind socket to device
    if (setsockopt(m_socket_fd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)) < 0) {
        close(); return;
    }
}

// Was the interface opened successfully?
bool ethernet_if::is_open() const
{
    return (m_socket_fd >= 0)
        && (m_interface_idx >= 0);
}

// Shut down this interface.
void ethernet_if::close()
{
    if (m_socket_fd >= 0) {
        ::close(m_socket_fd);
    }
    m_socket_fd = -1;
    m_interface_idx = -1;
}

uint32_t ethernet_if::send(const uint8_t* packet, uint32_t len)
{
    // Create a descriptor for the socket, and copies the destination MAC.
    struct sockaddr_ll socket_address;
    socket_address.sll_ifindex = m_interface_idx;
    socket_address.sll_halen = MAC_ADDRESS_SIZE;
    memcpy(socket_address.sll_addr, packet, MAC_ADDRESS_SIZE);

    // Send the packet to the Ethernet device.
    return sendto(m_socket_fd, packet, len, 0,
        (struct sockaddr*)&socket_address, sizeof(struct sockaddr_ll));
}

uint32_t ethernet_if::receive(uint8_t* packet, uint32_t len)
{
    // Return the number of bytes received
    return recv(m_socket_fd, packet, len, 0);

}

// Calculate Ethernet FCS (CRC32) for a given buffer and append it to end of buffer.
// Note: Requires 4 bytes of leftover space in buffer after end of packet.
uint32_t append_crc32(uint8_t* packet, unsigned len)
{
    // Byte-at-a-time algorithm using lookup table.
    uint32_t crc = 0xFFFFFFFFul;
    for (uint32_t i = 0; i < len; i++) {
        uint8_t index = (crc ^ (uint32_t) packet[i]) & 0xFFul;
        uint32_t value = CRC_TABLE[index];
        crc = (crc >> 8) ^ value;
    }
    crc = crc ^ 0xFFFFFFFFul;

    if (DEBUG_CRC_VERBOSE)
        printf(" crc is 0x%08X\n", crc);

    // Append to end of buffer
    // Note: This assumes host CPU is little-endian, which is safe for Rasp.Pi.
    union {
        uint32_t ui32;
        uint8_t ui8[4];
    } u;

    u.ui32 = crc;
    packet[len + 0] = u.ui8[0];
    packet[len + 1] = u.ui8[1];
    packet[len + 2] = u.ui8[2];
    packet[len + 3] = u.ui8[3];
    return len+4;
}
